package com.zigong.app.ui.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.util.ViewUtils;
import com.ruihang.generalibrary.ui.widget.CustomEXImageView;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.ui.widget.CustomLinearLayout;
import com.ruihang.generalibrary.utils.ListUtils;
import com.zigong.app.R;
import com.zigong.app.application.Cache;
import com.zigong.app.application.Constances;
import com.zigong.app.base.BaseActivity;
import com.zigong.app.base.BaseDetailActivity;
import com.zigong.app.beans.FOrganDetail;
import com.zigong.app.beans.NewsItem;
import com.zigong.app.beans.RssFeed;
import com.zigong.app.beans.RssItem;
import com.zigong.app.ui.adapter.CityStaHomepageAdapter;
import com.zigong.app.ui.util.RBaseItemDecoration;
import com.zigong.app.ui.utils.GlideCircleTransform;
import com.zigong.app.ui.utils.GlideUtil;
import com.zigong.app.ui.utils.RssFeed_SAXParser;
import com.zigong.app.ui.utils.TitleUtils;

import org.xml.sax.SAXException;

import java.io.IOException;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CountyStatePageActivity extends BaseDetailActivity implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener
        , CanRefreshLayout.IScrollView {

    @BindView(R.id.title_top_layout_edit)
    protected CustomFontTextView share;
    @BindView(R.id.city_sta_homepager_refreshLayout)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected CustomLinearLayout layout;
    @BindView(R.id.city_sta_home_page_icon)
    protected CustomEXImageView icon;
    @BindView(R.id.city_sta_home_page_hot)
    protected ImageView hot_icon;
    @BindView(R.id.city_sta_home_page_channelName)
    protected CustomFontTextView channelName;
    @BindView(R.id.city_sta_home_page_isSubscribe)
    protected CustomFontTextView status;
    @BindView(R.id.city_sta_home_page_list)
    protected RecyclerView video_list;
    private CityStaHomepageAdapter adapter;
    private LinearLayoutManager manager;
    private MotionEvent mCurrentMotion;
    private FOrganDetail detail;
    private int currentPage = 0;
    private int pageAll = 0;
    private static final int TO_CHOOSE_CITY = 1;
    public static final int REQUEST_CODE_LOGIN = 101;
    public static final String CHANNEL_SUBSCRIBE = "channel_isSubscribe";
    public static final String INIT_SUBSCRIBE = "init_isSubscribe";//是否需要初始化订阅状态
    public static final String HOT_TAG = "hot_tag";
    private String id, title, detailUrl;

    private Handler handler;
    private RssFeed feed;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        initView();
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if(msg.what == 1){
                    List<RssItem> list =  feed.getList();
//                    for(int i=0;i<list.size();i++){
//                        JLog.e("CountyStatePageActivity","----"+i+"--title-"+list.get(i).getTitle());
//                    }
                }
            }
        };
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_city_sta_homepage);
        ButterKnife.bind(this);
    }

    private void initView() {
        ImageView logoImg = (ImageView) findViewById(R.id.title_top_logo);
//        if (null != logoImg) {
//            logoImg.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    Intent intent = new Intent(CountyStatePageActivity.this, ChooseCityActivity.class);
//                    intent.putExtra(ChooseCityActivity.TITLE_KEY, Cache.getInstance().getChoosedCity());
//                    startActivityForResult(intent, TO_CHOOSE_CITY);
//                }
//            });
//        }
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        id = getIntent().getStringExtra(EX_ID);
        title = getIntent().getStringExtra(EX_TITLE);
        detailUrl = getIntent().getStringExtra(BaseActivity.EX_URL);
        String hotLevel = getIntent().getStringExtra(HOT_TAG);
        if (!TextUtils.isEmpty(hotLevel)) {
            if (hotLevel.equals("0")) {
                hot_icon.setImageResource(R.mipmap.icon_hot_high);
            } else if (hotLevel.equals("1")) {
                hot_icon.setImageResource(R.mipmap.icon_hot_mid);
            } else if (hotLevel.equals("2")) {
                hot_icon.setImageResource(R.mipmap.icon_hot_low);
            }
        }
        status.setVisibility(View.GONE);
        share.setVisibility(View.GONE);
        if (!TextUtils.isEmpty(title)) {
            channelName.setText(title);
        }
        manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        video_list.setLayoutManager(manager);
        video_list.setItemAnimator(new DefaultItemAnimator());
        video_list.addItemDecoration(new RBaseItemDecoration(2));
        layout.setiScrollView(this);
        refreshLayout.autoRefresh();

    }

    @Override
    public void onRefresh() {
        currentPage = 0;
        getDetailList(currentPage);
    }

    @Override
    public void onLoadMore() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.loadMoreComplete();
        } else {
            currentPage = currentPage + 1;
            if (currentPage < pageAll) {
                getDetailList(currentPage);
            }
        }
    }

    /**
     * 获取市州媒体详情数据
     *
     * @param calledPage
     */
    private void getDetailList(int calledPage) {
        if (TextUtils.isEmpty(detailUrl) || !detailUrl.endsWith(".json")) {
            toast("数据错误");
            return;
        }
        final String url = "http://www.people.com.cn/rss/politics.xml";

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    feed = new RssFeed_SAXParser().getFeed(url);
                    JLog.e("CountyStatePageActivity","------------feed size-------------"+feed.getList().size());
                    handler.sendEmptyMessage(1);
                } catch (ParserConfigurationException e) {
                    e.printStackTrace();
                } catch (SAXException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();


//        HttpUtils.getInstance().requestCXChannel( new Callback<String>() {
//            @Override
//            public void onResponse(Call<String> call,  Response<String> response) {
//                JLog.e("getDetailList onResponse", response.body().toString());
//            }
//
//            @Override
//            public void onFailure(Call<String> call, Throwable t) {
//                JLog.e("getDetailList onFailure", "");
//            }
//        } );
//        NetUtils.getNetAdapter().getOrganList(getOwnerName(), detailUrl, calledPage, new AbsNetCallBack<FOrganDetail>(FOrganDetail.class, calledPage) {
//            @Override
//            public void onSuc(FOrganDetail organDetal) {
//                if (organDetal != null) {
//                    detail = organDetal;
//                    pageAll = organDetal.getPageAll();
//                    currentPage = organDetal.getPageIndex();
//                    setDetailData(organDetal);
//                }
//            }
//
//            @Override
//            public void onEnd() {
//                super.onEnd();
//                onNetFinish();
//            }
//        });
    }


    private synchronized void onNetFinish() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        }
        if (refreshLayout.isLoading()) {
            refreshLayout.loadMoreComplete();
        }
        refreshLayout.setLoadMoreEnabled(currentPage + 1 < pageAll);
    }


    /**
     * 显示初始化市州媒体数据
     *
     * @param detail
     */
    private void setDetailData(FOrganDetail detail) {
        if (pageAll == 0) {
            pageAll = detail.getPageAll();
        }
        initInfo(detail);
        List<NewsItem> dynamicList = detail.getDynamicList();
        if (ListUtils.isListValued(dynamicList)) {
            for (int i = 0; i < dynamicList.size(); i++) {
                dynamicList.get(i).setNewsType(Constances.NEWS_TYPE_COUNTY);
            }
            if (currentPage == 0) {
                if (adapter == null) {
                    adapter = new CityStaHomepageAdapter(this, dynamicList);
                    video_list.setAdapter(adapter);
                } else {
                    adapter.setData(dynamicList);
                }
            } else {
                adapter.addDatas(dynamicList);
            }

        }

    }

    private void initInfo(FOrganDetail detail) {
        String imgUrl = detail.getInstitutionImage();
        GlideUtil.getGlid(this, imgUrl).error(R.mipmap.icon_circle_avatar)
                .placeholder(R.mipmap.icon_circle_avatar).transform(new GlideCircleTransform(this))
                .into(icon);
    }

    @OnClick(value = {R.id.title_top_layout_back, R.id.title_top_layout_edit, R.id.city_sta_home_page_isSubscribe})
    public void ItemClcik(View v) {
        switch (v.getId()) {
            case R.id.title_top_layout_back:
                finish();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        setResultes();
        super.onBackPressed();
    }

    private void setResultes() {
        Intent intent = getIntent();
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_LOGIN) {
            onRefresh();
        } else if (requestCode == TO_CHOOSE_CITY && resultCode == RESULT_OK) {
            finish();
        }
    }

    @Override
    public boolean canScrollUp(MotionEvent motionEvent) {
        if (video_list == null) {
            return false;
        }
        switch (motionEvent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mCurrentMotion = MotionEvent.obtain(motionEvent);
                return canScrolledUp(motionEvent);
            case MotionEvent.ACTION_MOVE:
                if (mCurrentMotion != null) {
                    return canScrolledUp(mCurrentMotion);
                } else {
                    return canScrolledUp(motionEvent);
                }
            default:
                mCurrentMotion = null;
                return canScrolledUp(motionEvent);
        }
    }

    @Override
    public boolean canScrollDown(MotionEvent motionEvent) {
        if (video_list == null) {
            return false;
        }
        if (ViewUtils.isTouchPointInView(video_list, motionEvent.getRawX(), motionEvent.getRawY(), 0)) {
            return ViewCompat.canScrollVertically(video_list, 1);
        } else if (ViewUtils.isTouchPointInView(video_list, motionEvent.getRawX(), motionEvent.getRawY(), 0)) {
            return ViewCompat.canScrollVertically(video_list, 1);
        }
        return false;
    }

    private boolean canScrolledUp(MotionEvent me) {
        if (ViewUtils.isTouchPointInView(video_list, me.getRawX(), me.getRawY(), 0)) {
            return ViewCompat.canScrollVertically(video_list, -1);
        } else if (ViewUtils.isTouchPointInView(video_list, me.getRawX(), me.getRawY(), 0)) {
            return ViewCompat.canScrollVertically(video_list, -1);
        }
        return false;
    }

}
